<?php
namespace Home\Controller;

class InvestController extends \Home\Controller\BaseController
{

	
	/**
	 * 查询投资记录
	 */
	public function investListBySelf()
	{
		$param = I('params');

		if(!$param) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		
		// 构造查询条件		
		$where['user_id'] = $this->user['userId'];
		if(I('data.id', '', '/^\d+$/', $param)) $where['id'] = $param['id'];
		$param['status']?$where['status'] = $param['status']:"";
		$where['id'] = $param['id'];
		if($param['type']){
			if($param['type'] == 2){
				$where['type']=array("in",array('2','5'));
			}else{
				$where['type']=$param['type'];
			}
		}else{
			$where['type']=array("in",array('1','4'));
		}

		$list = D('Invest')->searchInvest($where);
		$return = array('error' => 0, 'info' => $list[0]);
		$this->ajaxReturn($return);
	}
	
	/**
	 * 查询投资记录
	 */
	public function investList()
	{
		$param = I('params');
		if(!$param) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		// 返回字段
		$field = 'id,user_id,good_info,amount,create_time,order_no';

		// 构造查询条件
		$where = array();
		$where['user_id']=$this->user['userId'];
		if($param['status']){
			$where['status'] = $param['status'];
		}

		if($param['type']){
			if($param['type'] == 2){
				$where['type']=array("in",array('2','5'));
			}else{
				$where['type']=$param['type'];
			}
		}else{
			$where['type']=array("in",array('1','4'));
		}
		
		$option['page'] = I('data.page', '', '/^\d+$/', $param) ? $param['page'] : 1;
		$option['size'] = I('data.size', '', '/^\d+$/', $param) ? $param['size'] : 5;
		$list = D('Invest')->searchInvest($where, $option, 'create_time desc', $field);
		$this->ajaxReturn($this->result($list));
	}
	
	/**
	 * 下单
	 * @author 刘新
	 */
	public function addOrder()
	{
		$param = I('params');
		$data['user_id'] = $this->user['userId'];
		$auto = $param['auto'];//是否自动下单 1
		$type = $param['type'];
		$data['type'] = $type;//1 普通商品 2团购商品 3 砍价商品 4 捡便宜商品 5 超级团购商品
		$data['receipt_id'] = $param['receipt_id'];
		$data['postage'] = $param['postage'];
		$data['good_info'] = $param['good_info'];
		if($type == 2||$type == 5||$auto==1){
			$data['amount'] = floatval($param['amount']);
			$data['status'] = '2';
			$good_info = json_decode($data['good_info'],true)[0];
			$gooddata = M("Good")->where(array("id"=>$good_info['good_id']))->find();
			if($gooddata['stock'] == 0){
				$this->ajaxReturn(array("error"=>'1',"info"=>"数量不足"));
			}
			if($type == 2 || $type == 3){
				M("Good")->where(array("id"=>$good_info['good_id']))->save(array("stock"=>array('exp','stock-'.$good_info['count']),"total_count"=>array('exp','total_count+1')));
			}else{
				M("Good")->where(array("id"=>$good_info['good_id']))->save(array("stock"=>array('exp','stock-'.$good_info['count'])));
			}
			$res = D('Invest')->addOrder($data, $this->user['userId']);
			$good_info['invest_id'] = $res['info']['id'];
			$good_info['goods_id'] = $good_info['good_id'];
			$investgoods = M("InvestGoods")->add($good_info);
		}else{
			//购物车id
			$card_ids = explode(",",$param['card_ids']);
			$where_card['id'] = array("in",$card_ids);
			$cardinfo = M("Card")->where($where_card)->select();
			if(count($cardinfo)==0){
				$this->ajaxReturn(array("error"=>0,"info"=>"购物车不存在这些信息"));
			}
			$amount = 0;
			$investgoods = array();
			$type = 0;
			foreach($cardinfo as $key=>$val){
				if($val['status'] == 1){
					$good_info = array();
					$good_info["goods_id"] = $val['good_id'];
					$good_info["count"] = $val['count'];
					$good_info["price"] = $val['price'];
					$good_info["type"] = $val['type']?$val['type']:"";
					$amount += floatval($val['price'])*$val['count'];
					M("Good")->where(array("id"=>$val['good_id']))->save(array("stock"=>array('exp','stock-'.$val['count'])));
					$investgoods[] = M("InvestGoods")->add($good_info);
					$type = $val['type']?$val['type']:"0";
				}
			}
			$data['status'] = '2';
			$data['amount'] =floatval($amount);
			$res = D('Invest')->addOrder($data, $this->user['userId']);
			$where = array();
			$where['id'] = array("in",$investgoods);
			M("InvestGoods")->where($where)->save(array("invest_id"=>$res['info']['id']));
			if($type == 3){
				M("BargainOrder")->where(array("card_id"=>array("in",$card_ids)))->save(array("invest_id"=>$res['info']['id']));
			}
			M("Card")->where($where_card)->delete();
		}
		$this->ajaxReturn($res);
	}
	

	//修改订单状态
	public function changeinveststatus(){
		$param = I('params');
		$id = $param['id'];
		if(!$id) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		$status = $param['status'];
		$res = M("Invest")->where(array("id"=>$id))->save(array("status"=>$status));
		if($res){
			$return = array('error' => 0, 'info' => "修改成功");
		}else{
			$return = array('error' => 0, 'info' => "修改失败");
		}
		$this->ajaxReturn($return);
	}
	/**
	 * 计算运费
	 */
	public function returnpostage(){
		$param = I("params");
		$goodids = $param['goodid'];
		$goodid = explode(",",$goodids);
		$province = $param['province'];

		$where['id'] = array("in",$goodid);
		$goodlist = M("Good")->where($where)->select();
		$postage = 0;
		if(is_array($goodlist)){
			foreach($goodlist as $key=>$val){
				if(!in_array($province,explode(",",$val['freeprovince']))){
					$postage  += $val['postage'];
				}
			}
		}
		$this->ajaxReturn(array('error' => 0, 'info' => array("postage"=>floatval($postage))));
	}
	/**
	 * 订单数目
	 */
	public function ordernum(){
		$data['user_id'] = $this->user['userId'];
		$investinfo = M("Invest")->where($data)->select();
		$returninvest = array();
		if(is_array($investinfo)){
			foreach($investinfo as $key=>$val){
				if($val['status'] == '4'){
					$returninvest["receipt"] ++;
				}elseif($val['status'] == '5'){
					$returninvest["score"] ++;
				}elseif($val['status'] == '11'){
					$returninvest["refund"] ++;
				}elseif($val['status'] == '2'){
					$returninvest["waitpay"] ++;
				}elseif($val['status'] = "3"){
					$returninvest["deliver"] ++;
				}
			}
		}
		$this->ajaxReturn(array('error' => 0, 'info' =>$returninvest));
	}
	/**
	 * 投资收益
	 * @author 刘新
	 */
	public function profit()
	{
		$param = I('param');
	}
	//插入购物车
	public function setcard(){
		$param = I("params");
		if(empty($param['good_id'])||empty($param['count'])||empty($param['price'])||empty($param['type'])){
			$this->ajaxReturn(array('error' => 1, 'info' =>"参数不全"));
		}
		$data['good_id'] = $param['good_id'];
		$data['count'] = $param['count'];
		$data['price'] = $param['price'];
		$data['type'] = $param['type'];
		$data['status'] = '1';//1 正常 2 失效
		$data['user_id'] = $this->user['userId'];
		$data['create_time'] = time();
		$id = $param['id'];
		if(empty($id)){
			$info['id'] = M("Card")->add($data);
			$this->ajaxReturn(array('error' => 0, 'info' => $info));
		}else{
			M("Card")->where(array("id"=>$id))->save($data);
			$this->ajaxReturn(array('error' => 0, 'info' =>"修改成功"));
		}
	}
	//在购物车里面砍价
	public function bargainCard(){
		$param = I('params');
		$card_ids = explode(",",$param['card_ids']);
		$where['mt_card.id'] = array("in",$card_ids);
		$where['mt_card.type'] = '3';
		$cardinfo = M("Card")
			->join("left join mt_good on mt_card.good_id=mt_good.id")
			->join("left join mt_active_goods on mt_card.good_id=mt_active_goods.goods_id")
			->join("left join mt_active on mt_active.id=mt_active_goods.active_id")
			->where($where)
			->field("mt_card.*,mt_active.bargain_amount,mt_active.bargain_price")
			->select();
		foreach($cardinfo as $key=>$val){
			$bargain_amount = $val['bargain_amount'];//砍价金额
			$bargain_price = $val['bargain_price'];//最低金额
			$cardprice = $val['price'];
			$goods_id = $val['good_id'];
			$user_id = $val["user_id"];//购买用户id
			$card_id = $val['id'];
			if($bargain_price>$cardprice-$bargain_amount && $this->user['userId'] != $user_id){//订单已有价格-每次可砍金额大于底价才能执行
				//已经砍过价的也不能砍了
				$bargainedinfo = M("BargainOrder")->where(array("bargain_user"=>$this->user['userId'],"goods_id"=>$goods_id,"card_id"=>$card_id))->find();
				if(count($bargainedinfo)){
					continue;
				}
				M("Card")->where(array("card_id"=>$card_id))->save(array("price"=>array('exp','price-'.$bargain_amount)));//修改订单价格
				$data = array();
				$data['create_time'] = date("Y-m-d H:i:s");
				$data['bargained'] = $bargain_amount;
				$data['user_id'] = $user_id;
				$data['card_id'] = $card_id;
				$data['goods_id'] = $goods_id;
				$data['bargain_user'] =  $this->user['userId'];//砍价用户id
				M("BargainOrder")->add($data);
			}
		}
		$this->ajaxReturn(array('error' => 0, 'info' =>"修改成功"));
	}
	//删除购物车的商品
	public function deletecard(){
		$param = I("params");
		$id = $param['id'];
		$id = M("Card")->where(array("id"=>$id))->delete();
		$this->ajaxReturn(array('error' => 0, 'info' =>"删除成功"));
	}
	//购物车列表
	public function cardlist(){
		$data['mt_card.user_id'] = $this->user['userId'];
		$param = I("params");
		$type = $param['type'];
		$data['mt_card.type'] = $type?$type:'1';
		if($type == 1 || $type==4){
			$data['mt_card.type'] = array("in",array('1','4'));
		}
		$res = M("Card")
			->join("left join mt_good on mt_card.good_id=mt_good.id")
			->where($data)
			->field(array("mt_card.*","mt_good.img_path","mt_good.title","mt_good.original_price","mt_good.postage"))
			->select();
		$return = array();
		foreach($res as $key=>$val){
			$return[$key] = $val;
			$return[$key]['img_path'] = "http://114.215.209.229/".explode(",",$val['img_path'])[0];
			$return[$key]['count'] = intval($val['count']);
			$return[$key]['price'] = floatval($val['price']);
			$return[$key]['postage'] = $val['postage']?intval($val['postage']):0;
			$return[$key]['allowbargain'] = '0';
			//砍价商品
			if($val['type'] == '3'){
				$goods_id = $val['good_id'];
				$bargainorder = M("BargainOrder")->where(array("card_id"=>$val['id']))->select();
				$bargained = 0;
				foreach($bargainorder as $keys=>$vals){
					$bargained += $vals['bargained'];
				}
				$return[$key]['bargained'] = $bargained;//已经砍价多少
				$where['goods_id'] = $val['good_id'];
				$cardinfo = M("ActiveGoods")
					->join("left join mt_active on mt_active.id=mt_active_goods.active_id")
					->where($where)
					->field("mt_active.bargain_amount,mt_active.bargain_price")
					->find();
				$bargain_amount = $cardinfo['bargain_amount'];//砍价金额
				$bargain_price = $cardinfo['bargain_price'];//最低金额
				$cardprice = $val['price'];
				$user_id = $val['user_id'];
				if($bargain_price>$cardprice-$bargain_amount && $this->user['userId'] != $user_id) {//订单已有价格-每次可砍金额大于底价才能执行
					$return[$key]['allowbargain'] = '1';
				}
			}
		}
		$this->ajaxReturn(array('error' => 0, 'info' => $return));
	}
	/**
	 * 团购信息
	 */
	public function getgroupinfo(){
		$param = I("params");
		$grouporderid = $param['grouporderid'];

		$groupOrder =M("GroupOrder")->where(array("id"=>$grouporderid))->find();//获取团的基本信息
		if(empty($groupOrder)){
			$this->ajaxReturn(array('error' => 1, 'info' => "没有数据"));
		}
		$goods_id = $groupOrder['goods_id'];
		$groupgoods = M("Good")->where(array("id"=>$goods_id))->find();
		$return = array();
		$return['goods_id'] = $goods_id;
		$return['info'] = $groupgoods['info'];
		$return['original_price'] = floatval($groupgoods['original_price']);
		$return['discount_price'] = floatval($groupgoods['discount_price']);
		$return['create_time'] = strtotime($groupgoods['create_time']);
		$return['title'] = $groupgoods['title'];
		$return['type'] = '2';
		$return['sub_title'] = $groupgoods['sub_title'];
		$return['stock'] = intval($groupgoods['stock']);
		$img_path = explode(",", $groupgoods['img_path']);
		$groupgoods['img_path'] = array();
		if (is_array($img_path)) {
			foreach ($img_path as $ks => $vs) {
				if ($vs == "") {
					continue;
				}
				$groupgoods['img_path'][] = "http://114.215.209.229" . $vs;
			}
		}
		$return['img_path'] = $groupgoods['img_path'][0];
		$returninfo['goodinfo'] = $return;
		$end_time = strtotime($groupOrder['end_time'])-time();
		$returninfo['groupOrderInfo'] = $groupOrder;
		$returninfo['groupOrderInfo']['end_time'] = cutTime($end_time);
		//获取发起人信息用户信息
		$parentuserid = $groupOrder['parent_user_id'];
		$result = M("User")->join("left join mt_file on mt_user.avatar_id=mt_file.id")->where(array("mt_user.id"=>$parentuserid))->field("mt_user.id,nickname,mt_file.url")->find();
		$result['avatar_url'] = $result['url']?"http://114.215.209.229".$result['url']:'';
		$returninfo['groupOrderInfo']['parent_user_info'] = $result;

		//获取参与者的用户信息
		$subuserinfo = M("GroupOrderList")
			->join("left join mt_user on mt_group_order_list.sub_user_id=mt_user.id")
			->join("left join mt_file on mt_user.avatar_id=mt_file.id")
			->where(array("mt_group_order_list.grouporderid"=>$grouporderid))
			->field("mt_user.id,mt_user.nickname,mt_user.avatar_id,mt_file.url,mt_user.id")
			->select();
		if(count($subuserinfo)){
			foreach($subuserinfo as $key=>$val){
				$returninfo['join_userinfo'][$key]['nickname'] = $val['nickname'];
				$returninfo['join_userinfo'][$key]['id'] = $val['id'];
				$returninfo['join_userinfo'][$key]['join_time'] = $val['create_time'];
				$returninfo['join_userinfo'][$key]['avatar_url'] = $val['url']?"http://114.215.209.229".$val['url']:'';
			}
		}
		$this->ajaxReturn(array('error' => 0, 'info' => $returninfo));
	}
	//计算订单可使用的优惠卷
	public function getorderCoupon(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$amount = $param['amount'];
		$userCoupon = M("UserCoupon")
				->join("left join mt_coupon on mt_user_coupon.coupon_id=mt_coupon.id")
				->where(array("mt_user_coupon.user_id"=>$userId,
						"mt_user_coupon.status"=>'1',
						"mt_coupon.condition"=>array("lt",$amount)))->find();
		if(empty($userCoupon)){
			$this->ajaxReturn(array('error' => 1, 'info' => "优惠卷不存在"));
		}
		$this->ajaxReturn(array('error' => 0, 'info' => array("coupon_id"=>$userCoupon['coupon_id'],"discount_amount"=>floatval("10"))));
	}
}
